package com.smart.wap.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import com.smart.common.entities.enums.SmsScene;
import com.smart.common.entities.file.UploadResult;
import com.smart.manager.pop.entities.enums.HdState;
import com.smart.manager.pop.entities.enums.RegisterKind;
import com.smart.manager.pop.entities.models.PopBasicPoster;
import com.smart.manager.pop.entities.models.PopDisInviter;
import com.smart.manager.pop.entities.models.PopDisLevel;
import com.smart.manager.pop.entities.models.query.QPopActivityMain;
import com.smart.manager.pop.entities.models.query.QPopBasicPoster;
import com.smart.manager.pop.entities.models.query.QPopDisInviter;
import com.smart.manager.pop.entities.models.query.QPopDisLevel;
import com.smart.service.sms.SmsService;
import com.smart.utils.WorkAcl;
import com.smart.wap.bodys.BrokerCation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 公众号接口
 *
 * @author leo
 * @date 2023/11/08
 */

@Service
@RequiredArgsConstructor
@Slf4j
public class WebsiteMainService {

    private final SmsService smsService;


    /**
     * 获取个人信息
     *
     * @return {@link PopDisInviter}
     */
    public PopDisInviter getAccount() {
        Optional<PopDisInviter> oneOrEmpty = new QPopDisInviter().id.eq(WorkAcl.getLoginId()).setMaxRows(1).findOneOrEmpty();
        Assert.isFalse(oneOrEmpty.isEmpty(), "未查到账号!");
        return oneOrEmpty.get();
    }


    public List<Map<String, String>> getPostersAll(Boolean type) {
        QPopActivityMain register = new QPopActivityMain();
        if (type){
            register.kind.eq(RegisterKind.B2B);
        }else {
            register.kind.eq(RegisterKind.B2C);
        }
        List<Long> list = register.state.eq(HdState.NORMAL).select(QPopActivityMain.Alias.posterId).findSingleAttributeList();
        List<PopBasicPoster> posters = new QPopBasicPoster().id.in(list).findList();
        return posters.stream().map(x -> Map.of("id",x.getId().toString(), "url", x.getHttpUrl())).collect(Collectors.toList());
    }

    public void delPoster(String id){
        PopDisInviter account = getAccount();
        List<UploadResult> results = account.getImageUser().stream().filter(x -> !x.getUid().equals(id)).collect(Collectors.toList());
        List<UploadResult> resultsU = account.getImage().stream().filter(x -> !x.getUid().equals(id)).collect(Collectors.toList());
        Opt.ofNullable(results).ifPresent(x->account.setImageUser(x).update());
        Opt.ofNullable(resultsU).ifPresent(x->account.setImage(x).update());
    }


    /**
     * 发送验证码
     * @param smsScene
     * @param phoneNumber
     */
    public void getSmsCode(SmsScene smsScene , String phoneNumber) {
        smsService.sendCaptchaCode(smsScene, phoneNumber);
    }




    public void AgentAddUser(BrokerCation.AgentInfo body) {
        String phoneNumber = body.getPhone();
        if (!StrUtil.equals(body.getCode(), "000000")) {
            smsService.checkCaptchaCode(SmsScene.POP_REVISE, phoneNumber, body.getCode());
        }
        PopDisInviter account = getAccount();
        Optional<PopDisInviter> orEmpty = new QPopDisInviter().id.ne(account.getId()).phone.eq(body.getPhone()).setMaxRows(1).findOneOrEmpty();
        Assert.isTrue(orEmpty.isEmpty(),"手机号已被绑定!");
        BeanUtil.copyProperties(body, account);
        account.update();
    }


    /**
     *
     * 验证个人信息是否完全
     * @return {@link String}
     */
    public String testAndVerify() {
        PopDisInviter simpleAccount = getAccount();
        BrokerCation.agent agent = BeanUtil.copyProperties(simpleAccount, BrokerCation.agent.class);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Set<ConstraintViolation<BrokerCation.agent>> validate = factory.getValidator().validate(agent);
        if (!validate.isEmpty()) {
            StringBuilder stringBuilder = new StringBuilder();
            int i = 0;
            for (ConstraintViolation<BrokerCation.agent> violation : validate) {
                if (i == validate.size() - 1)
                    stringBuilder.append(violation.getMessage());
                else
                    stringBuilder.append(violation.getMessage()).append(",");
                i++;
            }
            return stringBuilder.toString();
        }
        return null;
    }

    public List<PopDisLevel> getGrade(){
        return new QPopDisLevel().findList();
    }




}
